package rtc.core.net.rpc;

import org.json.JSONObject;

import java.util.Collection;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;

import rtc.core.utils.Utils;

/**
 * Created by Administrator on 2018/2/24.
 */

public class BaseManager {
    private final ConcurrentHashMap<Integer,RpcCallback> mRpcCallbackMap = new ConcurrentHashMap<>();
    public void init(){

    }

    public void unInit(){

    }

    public void removeCallbacks(RpcCallback.IReference reference){
        if(reference == null){
            mRpcCallbackMap.clear();
        }else{
            Set<Integer> keys = mRpcCallbackMap.keySet();
            for(Integer key : keys){
                RpcCallback callback = mRpcCallbackMap.get(key);
                if(callback != null && reference.equals(callback.getReference())){
                    mRpcCallbackMap.remove(key);
                }
            }
        }
    }

    protected RpcEntity rpcCallSync(int appid, String fn, Map arg){
        return RpcManager.getInstance().rpcCallSync(appid,fn, Utils.globalSeq(),arg);
    }

    @SuppressWarnings("unchecked")
    protected <T> void rpcCall(int appid, String fn, Map arg,RpcCallback<T> cb,RpcEntity.Callable<T> callable){
        final int seq = Utils.globalSeq();
        mRpcCallbackMap.put(seq,cb);
        RpcManager.getInstance().rpcCall(appid, fn, seq,arg, new RpcEntity.Callback() {
            @Override
            public void onCallback(int code, String msg, JSONObject args, RpcEntity response) {
                T data = callable.onCall(code,msg,args,response);
                RpcCallback cb = mRpcCallbackMap.remove(seq);
                if(cb != null){
                    cb.onResult(code,msg,data,response);
                }
            }
        });
    }

    protected void registerCommands(RpcManager.IComponent component,List<Command> commands){
        RpcManager.getInstance().registerCommands(component,commands);
    }

    protected void unregisterCommands(RpcManager.IComponent component, List<Command> commands){
        RpcManager.getInstance().unregisterCommands(component,commands);
    }

    protected void unregisterCommandsAll(RpcManager.IComponent component){
        RpcManager.getInstance().unregisterCommandsAll(component);
    }
}
